<?php

namespace app\admin\controller\consult;

use app\admin\model\xlzxinfo\Xlzxinfo;
use app\common\controller\Backend;
use app\common\model\User;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Log;
/**
 * 咨询订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\consult\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\consult\Order;

        // \addons\mental\model\WxUser::push_template_messsage(689);
        // die('完成');
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user','xlzxinfo'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['username','nickname','mobile','avatar']);
                $row->getRelation('xlzxinfo')->visible(['full_name','phone','image']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     *
     * @return void
     */
    public function closed($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if($row->status ==3){
            $this->error(__('该订单已完成不可关闭'));
        }
        if($row->status ==4){
            $this->error(__('该订单已过期不可关闭'));
        }
        $params['status'] = 5;
        $params['close_time'] = time();
        $result = $row->allowField(true)->save($params);
        if ($result !== false) {
            //调用im,给小程序发送消息，该订单已结束。
            $data = \app\common\library\Ims::send_business_notification($ids);
            $this->success(__('操作成功'), $data);
        } else {
            $this->error(__('No rows were updated'));
        }
    }

    public function exchange($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $result = $this->model->where(['id'=>['in',$ids]])->update($params);
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        return $this->view->fetch();
    }


    /**
     * 订单退款，审核完成。
     * @param $ids
     * @return string
     * @throws \think\Exception
     */
    public function refund($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $refund = Db::name('refund_order')->where('order_id',$row->id)->where('refund_status',1)->find();
        if(!empty($refund)){
            $refund_reason = $refund['refund_reason'];
            $refund_notes = $refund['refund_notes'];
        }else{
            $refund_reason = '';
            $refund_notes = '';
        }
        $miao = Db::name('yunxin_calllog')->where(['order_id'=>$row['id']])->sum('duration');
        $danjia = bcdiv($row['price'],$row['minutes'],2);
        if($miao>0){
            $used_price  = ceil($miao / 60)*$danjia;
            $refund_price= ($row['minutes']-ceil($miao / 60))*$danjia;
        }else{
            $refund_price = $row['price'];
            $used_price = 0;
        }
        $row['used_fen'] = ceil($miao / 60);
        $row['used_price'] = $used_price;
        $row['refund_price'] = $refund_price;
        $row['refund_reason'] = $refund_reason;
        $row['refund_notes'] = $refund_notes;
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //通过
                    if($params['refund_status']==3){
                        //退款逻辑开始
                        //随机字符串，后面还得需要
                        $nonce_str = randstrpay();
                        //签名串
                        $sign_arr = [
                            'appid'=>'wx170fe8ce2ce8c283', //公众账号ID
                            'mch_id'=>'1612884628', //商户号
                            'nonce_str'=>$nonce_str,//随机字符串
                            'notify_url'=>"https://xyxl.ranxuxing.com/b.php/index/notify",
                            'out_refund_no'=>$row->id,//商户退款单号
                            'refund_fee'=>bcmul($refund_price,100),//退款金额 分
                            'refund_account'=>'REFUND_SOURCE_RECHARGE_FUNDS',
                            'refund_desc'=>$refund_reason,
                            'refund_fee_type'=>'CNY',
                            'sign_type'=>'MD5',//签名类型
                            'total_fee'=>bcmul($row->price,100),//订单金额 分
                            'transaction_id'=>$row->id,//微信生成的订单号
                        ];
                        //按照参数名ASCII字典序排序
                        $stringA =  ASCII($sign_arr);
                        //拼接APIv2密钥：
                        $stringB = $stringA."&key=".config('applet.secret_key');
                        //md5 生成签名给
                        $sign = strtoupper(MD5($stringB));

                        $refund_arr = [
                            'appid'=>'wx170fe8ce2ce8c283', //公众账号ID
                            'mch_id'=>'1612884628', //商户号
                            'nonce_str'=>$nonce_str,//随机字符串
                            'notify_url'=>"https://xyxl.ranxuxing.com/b.php/index/notify",
                            'out_refund_no'=>$row->id,//商户退款单号
                            'refund_fee'=>bcmul($refund_price,100),//退款金额 分
                            'refund_account'=>'REFUND_SOURCE_RECHARGE_FUNDS',
                            'refund_desc'=>$refund_reason,
                            'refund_fee_type'=>'CNY',
                            'sign_type'=>'MD5',//签名类型
                            'sign'=>$sign,
                            'total_fee'=>bcmul($row->price,100),//订单金额 分
                            'transaction_id'=>$row->id,//微信生成的订单号
                        ];

                        //生成请求xml
                        $xml = '<xml>';
                        foreach ($refund_arr as $key => $value) {
                            $xml .= '<' . $key . '>' . $value . '</' . $key . '>';
                        }
                        $xml .= '</xml>';
                        Log::info('进来请求退款');
                        Log::info('退款请求xml:'.$xml);
                        $result = refund_order_price(config('applet.refund_url'),$xml);
                        Log::info('退款result:'.$result);
                        //退款逻辑结束
                        if($result){
                            $res_xml=simplexml_load_file($result);
                            //返回值为 XML
                            if($res_xml->return_code=='SUCCESS' && $res_xml->return_msg=='OK'){
                                //更新订单表
                                $row_update['refund_status'] = 3;
                                $row_update['status'] = 5;//状态关闭
                                $row_update['close_time'] = time();//关闭时间
                                $res = $row->allowField(true)->save($row_update);
                                //更新退款申请表
                                Db::name('refund_order')->where(['order_id'=>$ids,'refund_status'=>1])->update(['return_msg'=>json_encode($result),'refund_status'=>3,'refund_price'=>$params['refund_price']]);
                                //并且还需要把咨询师的金额给追加上
                                //给咨询师分佣
                                $xlzxinfo = Xlzxinfo::where(['id'=>$row['xlzxinfo_id']])->find();
                                $commission_rate = Config::get('site.xlzx_commission_rate');
                                $commission_price = bcMath($used_price,$commission_rate/100,'*',2);
                                User::money($commission_price,$xlzxinfo['user_id'],'语音咨询订单佣金'.$commission_rate.'% <br/>咨询订单号:'.$row['id'].'<br/>订单编号'.$row['order_sn'],7,1);
                               //订单更改为已经完成分佣
                                \app\admin\model\consult\Order::where(['pay_status'=>'paid','id'=>$row['id']])->update(['is_rebate'=>1]);
                                Log::info('进来完成退款成功后的操作');
                            }
                        }
                    }
                    //驳回
                    if($params['refund_status']==2){
                        Db::name('refund_order')->where(['order_id'=>$ids,'refund_status'=>1])->update(['refund_status'=>2,'refund_reject'=>$params['refund_reject'],'refund_price'=>$params['refund_price']]);
                        $up = [
                            'refund_status'=>2,
                            'is_refund'=>0,
                        ];
                        $result = $row->allowField(true)->save($up);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
